// XOverGeneOp
// Copyright (c) 1998-2003 Matthew Faupel
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Library Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Library Public License for more details.
//
// You should have received a copy of the GNU Library Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
// 
// This Java class is inspired in part by the GAGS C++ library which I
// presume to be copyright J. J. Merelo <jmerelo@kal-el.ugr.es>.

package com.micropraxis.gajit;

import java.util.ArrayList;

/**
 * A class that represents a binary genetic operator that performs a single gene
 * crossover between two chromosomes.
 * 
 * @author gajit@micropraxis.com
 * @version 0.2
 */
public class XOverGeneOp extends GenOp
{

	public XOverGeneOp(int geneLength)
	{
		super(true);
	}

	public Chrom apply(Chrom chrom1, Chrom chrom2)
	{
		Chrom shorter;

		if (chrom1.size() < chrom2.size())
			shorter = chrom1;
		else
			shorter = chrom2;

		return applyAt(selectGene(shorter), chrom1, chrom2);
	}

	public Chrom applyAt(int index, Chrom chrom1, Chrom chrom2)
	{
		ArrayList<ArrayList<Integer>> bs = new ArrayList<ArrayList<Integer>>(2);
		
		int chrom1Ind = 1;
		int chrom2Ind = 1;
		
		if(chrom1.get(index).size() == 2)
		{
			chrom1Ind = index;
		}
		else if((chrom1.get(index).size() == 3))
		{
			chrom1Ind = index - 1;
		}
		
		if(chrom2.get(index).size() == 2)
		{
			chrom2Ind = index;
		}
		else if((chrom2.get(index).size() == 3))
		{
			chrom2Ind = index - 1;
		}
		
		bs.add(chrom1.get(chrom1Ind));
		bs.add(chrom1.get(chrom1Ind + 1));
		
		chrom1.set(chrom1Ind, chrom2.get(chrom2Ind));
		chrom1.set(chrom1Ind, chrom2.get(chrom2Ind + 1));
		
		chrom2.set(chrom2Ind, bs.get(0));
		chrom2.set(chrom2Ind + 1, bs.get(1));

		return (Chrom) chrom1;
	}
}
